package com.hm.base.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hm.base.auto.su.BeanUtil;
import com.hm.base.def.RequestMethodEnum;
import com.hm.base.domain.ReqLog;
import com.hm.base.mapper.ReqLogMapper;
import com.hm.base.vo.ReqLogVo;
import com.hm.common.def.DataStatusDef;
import com.hm.common.exception.ErrorCode;
import com.hm.common.exception.ServiceException;
import com.hm.common.su.bean.PageInfo;
import com.hm.common.su.bean.PageInfo.PageParam;
import com.hm.common.util.BeanToMapUtil;
import com.hm.common.util.CommonUtil;
import com.hm.common.util.DateUtil;
import com.hm.common.util.StringUtil;

/**
 * @author shishun.wang
 * @date 2018年3月9日 下午2:09:51
 * @version 1.0
 * @describe
 */
@Service
public class ReqLogServiceImpl implements ReqLogService {

	@Autowired
	private ReqLogMapper reqLogMapper;

	@Override
	public void addReqLog(ReqLogVo reqLogVo) {
		if (CommonUtil.isAnyEmpty(reqLogVo.getPlatform(), reqLogVo.getModule())) {
			throw ServiceException.warning(ErrorCode.REQUIRED_PARAMETERS_MISSING);
		}
		ReqLog reqLog = new ReqLog();
		BeanUtil.copyProperties(reqLogVo, reqLog);
		reqLog.setId(null);
		reqLog.setCreateTime(new Date());
		reqLog.setStatus(DataStatusDef.ENABLE.name());

		reqLogMapper.insert(reqLog);
	}

	@Override
	public PageInfo<ReqLogVo> query(PageParam pageParam, String platform, String module, RequestMethodEnum method, Long startCreateTime, Long endCreateTime) {
		Map<String, Object> params = new HashMap<String, Object>();
		if (!StringUtil.isBlankOrNull(platform)) {
			params.put("platform", platform);
		}
		if (!StringUtil.isBlankOrNull(module)) {
			params.put("module", module);
		}
		if (CommonUtil.isNotEmpty(method)) {
			params.put("method", method.name());
		}
		if (CommonUtil.isNotEmpty(startCreateTime)) {
			params.put("startCreateTime", new Date(startCreateTime));
		}
		if (CommonUtil.isNotEmpty(endCreateTime)) {
			params.put("endCreateTime", new Date(endCreateTime));
		}

		Page<Map<String,Object>> page = PageHelper.startPage(pageParam.getPage(), pageParam.getSize(), true);
		reqLogMapper.query(params);

		if (CommonUtil.isEmpty(page.getResult())) {
			return new PageInfo<ReqLogVo>(new ArrayList<ReqLogVo>(0), page.getPages(), page.getTotal());
		}

		return new PageInfo<ReqLogVo>(page.getResult().parallelStream().map(item -> {
			
			ReqLogVo vo = (ReqLogVo) BeanToMapUtil.Sample.mapToObject(item, ReqLogVo.class);
			vo.setCreateTime(DateUtil.data2long((Date) item.get("create_time")));
			
			return vo;
		}).collect(Collectors.toList()), page.getPages(), page.getTotal());
	}

}
